
from whiff import resolver
from whiff import gateway
from whiff.resources import PageShadow
from whiff.resources import FileByLines
from whiff.resources import inMemorySession
from whiff.resources import FreshName
from whiff.resources import sessionDirectory
from whiff.middleware import displayTraceback
import root
import os
from root import header_trailer

def application(sessionDir="/tmp/sessions", shadowdir="/tmp/shadowfiles", profileDir="/tmp/profiles"):
    testapp = resolver.moduleRootApplication("/", root,
                                         filter_middleware=root.header_trailer.__middleware__,
                                         #exception_middleware=None,
                                         #exception_middleware=displayTraceback.__middleware__,
                                         on_not_found=None, # show traceback (could comment)
                                         )
    # install resources in the testapp
    if sessionDir is None:
        sessionFinder = inMemorySession.memorySessionFinder(timeout=60) # 1 minute timeout
    else:
        if not os.path.exists(sessionDir):
            #pr "creating sessiondir", sessionDir
            os.mkdir(sessionDir)
            os.chmod(sessionDir, int("777", 8))
        sessionFinder = sessionDirectory.directorySessionFinder(directory=sessionDir, timeout=60)
    if profileDir is None:
        profileFinder = inMemorySession.memoryProfileFinder()
    else:
        if not os.path.exists(profileDir):
            #pr "creating profiledir", profileDir
            os.mkdir(profileDir)
            os.chmod(profileDir, int("777", 8))
        profileFinder = sessionDirectory.directoryProfileFinder(directory=profileDir)
    commentfinder = gateway.FileFinder("secretpassword", "/tmp/comments.txt")
    filefinder = gateway.FileFinder("secretpassword", "/tmp/testfile.txt")
    linesfinder = FileByLines.LineFinder("/usr/share/dict/words")
    namefinder = FreshName.FreshNameFinder()
    if not os.path.exists(shadowdir):
        os.mkdir(shadowdir)
        os.chmod(shadowdir, int("777", 8))
    shadowfinder = PageShadow.ShadowPageFinder(shadowdir)
    testapp.registerResourceFinder(prefix="freshName", finder=namefinder)
    testapp.registerResourceFinder(prefix="session", finder=sessionFinder)
    testapp.registerResourceFinder(prefix="profile", finder=profileFinder)
    testapp.registerResourceFinder(prefix="comments", finder=commentfinder)
    testapp.registerResourceFinder(prefix="datafile", finder=filefinder)
    testapp.registerResourceFinder(prefix="lines", finder=linesfinder)
    testapp.registerResourceFinder(prefix="shadow", finder=shadowfinder)
    return testapp

if __name__=="__main__":
    import wsgiref.simple_server
    print "serving wsgi at 8888"
    testapp = application()
    srv = wsgiref.simple_server.make_server('localhost', 8888, testapp)
    srv.serve_forever()
                    
